package com.ruoyi.controller;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.param.IAlreadyRead;
import com.param.impl.AlreadyRead;
import com.ruoyi.center.domain.NoticeCenter;
import com.ruoyi.center.service.INoticeCenterService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;

import io.swagger.annotations.ApiOperation;

import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 通知中心Controller
 * 
 * @author 王强
 * @date 2024-01-23
 */
@RestController
@RequestMapping("/center/center")
public class NoticeCenterController extends BaseController
{
    @Autowired
    private INoticeCenterService noticeCenterService;

    TokenService tokenService;
    
    ISysUserService sysUserService;
    
    @Autowired
    public void setSysUserService(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }
    
    @Autowired
    public void setTokenService(TokenService tokenService) {
    	this.tokenService = tokenService;
    }
    

    @PreAuthorize("@ss.hasPermi('center:center:query')")
    @PostMapping("listStatics")
    public AjaxResult listStatics(NoticeCenter noticeCenter, HttpServletRequest httpServletRequest)
    {
    	parseUser(noticeCenter);
    	
        return success(noticeCenterService.getStaticisList(noticeCenter));
    }
    
    /**
     * 查询通知中心列表
     */
    @PreAuthorize("@ss.hasPermi('center:center:list')")
    @GetMapping("/list")
    public TableDataInfo list(NoticeCenter noticeCenter, HttpServletRequest httpServletRequest)
    {
    	parseUser(noticeCenter);
    	
        startPage();
        List<NoticeCenter> list = noticeCenterService.selectList(noticeCenter);
        return getDataTable(list);
    }


	private void parseUser(NoticeCenter noticeCenter) {
    	
    	
    	Long userId = getUserId();
		SysUser selectUserById = sysUserService.selectUserById(userId);
    	
    	List<SysRole> roles = selectUserById.getRoles();
    	
    	int[] rolesIds = new int[] {0, 0};
    	
 
    	int editAndAdmin = 1;
    	
    	
    	
    	for (SysRole sysRole : roles) {
			
			String roleKey = sysRole.getRoleKey();
			
			boolean isEdit = roleKey.equals("order:manager:edit");
			if (isEdit) {
				 rolesIds[0] = (userId.intValue());
				 editAndAdmin++; 
    		}
    		
			boolean isAdmin = roleKey.equals("tyadmin");
			if (isAdmin) {
				 rolesIds[1] = (userId.intValue());
				 editAndAdmin++; 
			}
			
			
			
		}
    	
    	if (editAndAdmin == 3) { // edit and admin
            noticeCenter.setAuthority(3);
            return;
        }
    	
    	if (0 != rolesIds[1]) { // 管理人员
//    		noticeCenter.setAdminId(rolesIds[1]);
    		noticeCenter.setAuthority(1);
    		return;
    	}
    	
    	if (0 != rolesIds[0]) { // 编辑
    		noticeCenter.setAuthority(2);
    		noticeCenter.setAdminId(rolesIds[0]);
    	}
	}

    /**
     * 导出通知中心列表
     */
    @PreAuthorize("@ss.hasPermi('center:center:export')")
    @Log(title = "通知中心", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NoticeCenter noticeCenter)
    {
        List<NoticeCenter> list = noticeCenterService.selectList(noticeCenter);
        ExcelUtil<NoticeCenter> util = new ExcelUtil<NoticeCenter>(NoticeCenter.class);
        util.exportExcel(response, list, "通知中心数据");
    }

    /**
     * 获取通知中心详细信息
     */
    @PreAuthorize("@ss.hasPermi('center:center:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(noticeCenterService.selectById(id));
    }

    /**
	 * 全部已读
	 * 
	 * @param <V>
	 * @param param
	 * @return
	 * Long userId = getUserId();
		SysUser selectUserById = sysUserService.selectUserById(userId);
    	
    	List<SysRole> roles = selectUserById.getRoles();
    	
    	IAlreadyRead alreadyRead = new AlreadyRead();
    	
    	alreadyRead.setPlatform((byte) 1);
    	
    	for (SysRole sysRole : roles) {
			
    		if (sysRole.getRoleKey().equals("order:manager:edit")) {
    			alreadyRead.setPlatform((byte) 2);
    			break;
    		}
    		
    		
		}
	 */
	@PostMapping("/allAlreadRead")
	@ApiOperation(value = "全部已读")
	public AjaxResult allAlreadRead() {
		
		Long userId = getUserId();
		SysUser selectUserById = sysUserService.selectUserById(userId);
    	
    	List<SysRole> roles = selectUserById.getRoles();
    	
    	NoticeCenter alreadyRead = new NoticeCenter();
    	
    	alreadyRead.setPlatform(1);
    	
    	String roleKey;
    	
    	int flags = 0;
    	
    	for (SysRole sysRole : roles) {
			
			roleKey = sysRole.getRoleKey();
			if (roleKey.equals("order:manager:edit")) {
    			flags = 2;
    		} else if (roleKey.equals("tyadmin")) {
    			flags =  1;
    			break;
			}
		}
    	
    	if (flags == 2) {
			alreadyRead.setAuthority(2);
			alreadyRead.setAdminId(userId.intValue());
    	} else if (flags == 1) {
    		alreadyRead.setAuthority(1);
    	}
		
		return success(noticeCenterService.allAlreadRead(alreadyRead));
	}

    
    /**
     * 新增通知中心
     */
    @PreAuthorize("@ss.hasPermi('center:center:add')")
    @Log(title = "通知中心", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody NoticeCenter noticeCenter)
    {
        return toAjax(noticeCenterService.insert(noticeCenter));
    }

    /**
     * 修改通知中心
     */
    @PreAuthorize("@ss.hasPermi('center:center:edit')")
    @Log(title = "通知中心", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改信息")
    public AjaxResult edit(@RequestBody NoticeCenter noticeCenter)
    {
        return toAjax(noticeCenterService.update(noticeCenter));
    }

    /**
     * 删除通知中心
     */
    @PreAuthorize("@ss.hasPermi('center:center:remove')")
    @Log(title = "通知中心", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(noticeCenterService.deleteByIds(ids));
    }
}
